import { Service } from 'egg';

export default class Version extends Service {
  async get(version: string) {
    let res = await this.app.mysql.get('version', {
      version
    });
    return res;
  }

  async create(version: string, file: Buffer, filePath: string, remark: string, autopublic?: boolean) {
    file;
    let res = await this.app.mysql.insert('version', {
      version,
      // package: file,
      package: null,
      package_path: filePath,
      remark,
      public: autopublic ? 1 : 0
    });
    return res.affectedRows === 1;
  }

  async uploadToOss(version: string, file: string) {
    const { ctx } = this;
    const path = `${ctx.oss.options.bucket}/public/apaas/apaas-ide/${version}.zip`;
    try {
      ctx.oss;
      let res = await ctx.oss.put(path, file);
      console.log('res', res);
      if (res) {
        if (res.url) {
          return res.url;
        }
      }
    } catch (e) {
      console.error(e);
    }
  }

  async update(id: string, newData: any) {
    console.log('update', id);
    let res = await this.app.mysql.update(
      'version',
      {
        ...newData
      },
      {
        where: {
          id
        }
      }
    );
    return res.affectedRows === 1;
  }

  /**
   * 获取最新版本信息
   * @param version 现有版本
   */
  async getLatest(version?: string) {
    if (!version) {
      let res = await this.app.mysql.query(
        'select * from version where public = 1 order by id desc'
      );
      return res && res[0];
    }
    const query = `select * from version where version like '${version}%' and public = 1 order by id desc`;
    let res = await this.app.mysql.query(query);
    return res && res[0];
  }

  async getList() {
    return await this.app.mysql.select('version', {
      orders: [['id', 'desc']],
      limit: 100
    });
  }

  async getById(id: number) {
    let res = await this.app.mysql.select('version', {
      where: {
        id
      }
    });
    console.log('getById---------------------', id, res.length);
    return res && res[0];
  }
}
